package logic

import (
	"context"
	"errors"
	"smsbridge/models/cache"
	"smsbridge/models/mysql"
	"smsbridge/pkg"

	"smsbridge/smsrpc/internal/svc"
	"smsbridge/smsrpc/smsrpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *smsrpc.RegisterRequest) (*smsrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "smsTwo"+in.Username).Result()
	if result != in.Sms {
		return nil, errors.New("短信验证码错误")
	}
	resul, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Username).Result()
	if resul != in.Captcha {
		return nil, errors.New("图型验证码错误")
	}
	var user mysql.User
	user = mysql.User{
		Model:    gorm.Model{},
		Username: in.Username,
		Password: pkg.Md5(in.Password),
	}
	err := user.RegisterAdd(mysql.DB)
	if err != nil {
		return nil, err
	}
	return &smsrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
